#!/usr/bin/env python3
# -*- coding: utf-8 -*-
################################
# File Name   : save_password.py
# Author      : liyanqing
# Created On  : 2021-08-16 20:11:25
# Description : 
################################
import os
import re
import sys
import argparse

sys.path.append(str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/common')
import common_password

os.environ['PYTHONUNBUFFERED'] = '1'

def read_args():
    """
    Read in arguments.
    """
    current_user = os.popen('whoami').read().strip()
    parser = argparse.ArgumentParser()

    parser.add_argument('-P', '--password_file',
                        default=str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config/password.encrypted',
                        help='Specify the user password file, default is "' + str(os.environ['BATCH_RUN_INSTALL_PATH']) + '/config/password.encrypted".')
    parser.add_argument('-u', '--user',
                        default=current_user,
                        help='Specify user name, deault is current user.')
    parser.add_argument('-p', '--password',
                        required=True,
                        default='',
                        help='Specify user password.')

    args = parser.parse_args()

    return(args.password_file, args.user, args.password)


class SavePassword():
    def __init__(self, password_file, user, password):
        self.password_file = password_file
        self.user = user
        self.password = password

    def get_user_list(self):
        user_list = []

        if os.path.exists(self.password_file):
            with open(self.password_file, 'r') as PF:
                for line in PF.readlines():
                    if re.match('^\s*$', line) or re.match('^\s*#.*$', line):
                        continue
                    elif re.match('^\s*(.+?)\s+(.+)\s*$', line):
                        my_match = re.match('^\s*(.+?)\s+(.+)\s*$', line)
                        user = my_match.group(1)

                        if user not in user_list:
                            user_list.append(user)

        return(user_list)

    def run(self):
        user_list = self.get_user_list()

        if self.user in user_list:
            print('*Warning*: user "' + str(self.user) + '" exists on user password file "' + str(self.password_file) + '", will not re-write it.')
        else:
            try:
                with open(self.password_file, 'a') as PF:
                    encrypted_password = common_password.encrypt(self.password)
                    PF.write(str(self.user) + '  ' + str(encrypted_password) + '\n')
            except Exception as error:
                print('*Error*: Failed on open file "' + str(self.password_file) + '" for write, ' + str(error))
                sys.exit(1)
 

################
# Main Process #
################
def main():
    (password_file, user, password) = read_args()
    my_save_password = SavePassword(password_file, user, password)
    my_save_password.run()

if __name__ == '__main__':
    main()
